package cn.glenn._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT = 3;
    private static final int WINDOWS_SIZE_SECONDS = 60;

    private final ConcurrentHashMap<String,Integer> clientCounter = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastResetTimes = new ConcurrentHashMap<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.debug("进入网站限流拦截器");
      String addr = request.getRemoteAddr();
      LocalDateTime lastResetTime = lastResetTimes.get(addr);
      if (lastResetTime == null || LocalDateTime.now().isAfter(lastResetTime.plusSeconds(WINDOWS_SIZE_SECONDS))) {
          clientCounter.put(addr,0);
          lastResetTimes.put(addr,LocalDateTime.now());
      }
      Integer i = clientCounter.merge(addr,1,Integer::sum);
      log.debug("第{}次",i);
      if (i>MAX_REQUEST_COUNT) {
          throw new RuntimeException("访问过于频繁，请您稍后再试");
      }
      return true;
    }
}
